package com.cbs.android.module.user.user.module;

import android.os.AsyncTask;
import android.os.Message;

import com.cbs.android.component.applicationutils.network.ErrorResponse;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.user.user.handler.ModuleHandler;
import com.cbs.android.module.user.user.handler.UserChangeHandler;
import com.google.gson.Gson;

/**
 * Created by broche on 2/2/16.
 */
public class LogoutModule extends AsyncTask<Object, Object, Message> {
    private static final String TAG = LogoutModule.class.getName();
    private UserChangeHandler userChangeHandler;
    private ModuleHandler moduleHandler = null;
    private static final int MSG_CANCELED = 1;
    private static final int MSG_SUCCESS = 2;

    public LogoutModule(UserChangeHandler userChangeHandler, ModuleHandler moduleHandler) {
        if (userChangeHandler == null) {
            this.userChangeHandler = UserModule.getDefaultLogoutUserChangeHandler();
        } else {
            this.userChangeHandler = userChangeHandler;
        }
        this.moduleHandler = moduleHandler;
    }

    @Override
    protected Message doInBackground(Object... params) {
        Message message = new Message();
        if (userChangeHandler != null) {
            String hint = userChangeHandler.shouldChange();
            if (hint != null) {
                message.what = MSG_CANCELED;
                message.obj = hint;
                return message;
            }
        }
        UserModule.setUser(null);
        if (userChangeHandler != null) {
            userChangeHandler.onChanged(null);
        }

        message.what = MSG_SUCCESS;
        return message;
    }

    @Override
    protected void onPostExecute(Message message) {
        if (message.what == MSG_CANCELED) {
            if (moduleHandler != null) {
                ErrorResponse errorResponse = new ErrorResponse();
                errorResponse.setErrorNo(99998);
                errorResponse.setErrorMsg((String) message.obj);
                moduleHandler.onFailure(999, new Gson().toJson(errorResponse));
            }
        } else if (message.what == MSG_SUCCESS) {
            if (moduleHandler != null) {
                moduleHandler.onSuccess(null);
            }
        }
    }
}
